let ue = UE.getEditor("remark");
$(function () {
    createProApprovalUser();
    jeDate("#beginTime", {
        format: "YYYY-MM-DD"
    });
    jeDate("#endTime", {
        format: "YYYY-MM-DD"
    });
    jeDate("#beginTimeQuery", {
        format: "YYYY-MM-DD"
    });
    jeDate("#endTimeQuery", {
        format: "YYYY-MM-DD"
    });
    $(".js-simple-query").unbind("click").click(function () {
        $("#myTable").bootstrapTable("refresh");
    })
    $("#cbut").unbind("click").click(function () {
        document.getElementById("form1").reset();
        $("#show_attach").html("");
        $("#attach").attr("data_value", "");
        ue.setContent("");
        $("#joinDept").attr("data-value", "");
        $("#taskUsers").attr("data-value", "");
        $("#proSort").attr("data-value", "");
        $("#createProjectModal").modal("show");
        $(".js-send").unbind("click").click(function () {
            insertProRecord();
        })
    })
    query("");
    $.ajax({
        url: "/ret/proget/getProSortTree",
        type: "post",
        dataType: "json",
        success: function (data) {
            var topNode = [{
                sortName: "TOP分类",
                isParent: "false",
                sortId: ""
            }];
            var newTreeNodes = topNode.concat(data);
            $.fn.zTree.init($("#menuTree"), setting1, newTreeNodes);
        }
    });
    $("#proSort").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#menuContent").css({
            "width": $(this).outerWidth() + "px"
        }).slideDown(200);
    });
    $("body").unbind("click").click(function () {
        $("#menuContent").hide();
    });
    $("#menuContent").unbind("click").click(function (e) {
        e.stopPropagation();
    });

    $(".js-status").unbind("click").click(function () {
        let status = $(this).attr("data-value");
        $("#myTable").bootstrapTable('destroy');
        query(status);
    })
    getProRecordStatusCountList();

})

function insertProRecord() {
    if ($("#title").val() == "") {
        layer.msg("项目标题不能为空！");
        return;
    }
    $.ajax({
        url: "/set/proset/insertProRecord",
        type: "post",
        dataType: "json",
        data: {
            sortNo: $("#sortNo").val(),
            proCode: $("#proCode").val(),
            title: $("#title").val(),
            proSort: $("#proSort").attr("data-value"),
            approvalUser: $("#approvalUser").val(),
            proLevel: $("#proLevel").val(),
            beginTime: $("#beginTime").val(),
            endTime: $("#endTime").val(),
            manager: $("#manager").attr("data-value"),
            budget: $("#budget").val(),
            joinDept: $("#joinDept").attr("data-value"),
            taskUsers: $("#taskUsers").attr("data-value"),
            remark: ue.getContent(),
            attach: $("#attach").attr("data_value"),
            isCreateFile: getCheckBoxValue("isCreateFile")
        },
        success: function (data) {
            if (data.status == "200") {
                layer.msg(sysmsg[data.msg]);
                $("#createProjectModal").modal("hide");
                $("#myTable").bootstrapTable("refresh");
                getProRecordStatusCountList();
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }

        }
    });
}

function updateProRecord(proId) {
    if ($("#title").val() == "") {
        layer.msg("项目标题不能为空！");
        return;
    }
    $.ajax({
        url: "/set/proset/updateProRecord",
        type: "post",
        dataType: "json",
        data: {
            proId: proId,
            sortNo: $("#sortNo").val(),
            proCode: $("#proCode").val(),
            title: $("#title").val(),
            proSort: $("#proSort").attr("data-value"),
            approvalUser: $("#approvalUser").val(),
            proLevel: $("#proLevel").val(),
            beginTime: $("#beginTime").val(),
            endTime: $("#endTime").val(),
            manager: $("#manager").attr("data-value"),
            budget: $("#budget").val(),
            joinDept: $("#joinDept").attr("data-value"),
            taskUsers: $("#taskUsers").attr("data-value"),
            remark: ue.getContent(),
            attach: $("#attach").attr("data_value"),
            isCreateFile: getCheckBoxValue("isCreateFile")
        },
        success: function (data) {
            if (data.status == "200") {
                layer.msg(sysmsg[data.msg]);
                $("#createProjectModal").modal("hide");
                $("#myTable").bootstrapTable("refresh");
                getProRecordStatusCountList();
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }

        }
    });
}

function query(status) {
    $("#myTable").bootstrapTable({
        url: '/ret/proget/getProRecordListByStatus?status=' + status,
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toobar',//工具列
        striped: true,//隔行换色
        cache: false,//禁用缓存
        pagination: true,//启动分页
        sidePagination: 'server',//分页方式
        pageNumber: 1,//初始化table时显示的页码
        pageSize: 10,//每页条目
        showFooter: false,//是否显示列脚
        showPaginationSwitch: true,//是否显示 数据条数选择框
        sortable: true,//排序
        search: true,//启用搜索
        sortOrder: "asc",
        showColumns: true,//是否显示 内容列下拉框
        showRefresh: true,//显示刷新按钮
        idField: 'proId',//key值栏位
        clickToSelect: true,//点击选中checkbox
        pageList: [10, 20, 30, 50],//可选择单页记录数
        queryParams: queryParams,
        columns: [{
            checkbox: true
        }, {
            field: 'num',
            title: '序号',//标题  可不加
            width: '50px',
            formatter: function (value, row, index) {
                return index + 1;
            }
        }, {
            field: 'proCode',
            width: '50px',
            title: '项目编号'
        }, {
            field: 'title',
            width: '150px',
            title: '项目名称',
            formatter:function (value,row,index)
            {
                return "<a href=\"javascript:void(0);details('" + row.proId + "')\" style='cursor: pointer'>"+value+"</a>";
            }
        }, {
            field: 'sortName',
            width: '50px',
            title: '项目分类'
        }, {
            field: 'proLevel',
            width: '50px',
            title: '项目等级',
            formatter: function (value, row, index) {
                if (value == "0") {
                    return "一般";
                } else if (value == "1") {
                    return "普通";
                } else if (value == "2") {
                    return "重点";
                }
            }
        }, {
            field: 'beginTime',
            width: '50px',
            title: '开始时间'
        }, {
            field: 'endTime',
            width: '50px',
            title: '结束时间'
        }, {
            field: 'managerUserName',
            width: '50px',
            title: '项目经理'
        }, {
            field: 'status',
            width: '50px',
            title: '当前状态',
            formatter: function (value, row, index) {
                if (value == "0") {
                    return "立项中";
                } else if (value == "1") {
                    return "已驳回";
                } else if (value == "2") {
                    return "审批中";
                } else if (value == "3") {
                    return "处理中";
                } else if (value == "4") {
                    return "已挂起";
                } else if (value == "5") {
                    return "已完成";
                }
            }
        }, {
            field: 'opt',
            title: '操作',
            align: 'center',
            width: '150px',
            formatter: function (value, row, index) {
                return createOptBtn(row.proId, row.status);
            }
        }],
        onClickCell: function (field, value, row, $element) {
            //alert(row.SystemDesc);
        },
        responseHandler: function (res) {
            if (res.status == "500") {
                console.log(res.msg);
            } else if (res.status == "100") {
                layer.msg(sysmsg[res.msg]);
            } else {
                return {
                    total: res.list.total, //总页数,前面的key必须为"total"
                    rows: res.list.list
                    //行数据，前面的key要与之前设置的dataField的值一致.
                };
            }
        }
    });
}

function queryParams(params) {
    var temp = {
        search: params.search,
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        sort: params.sort,
        sortOrder: params.order,
        proLevel: $("#proLevelQuery").val(),
        endTime: $("#endTimeQuery").val(),
        beginTime: $("#beginTimeQuery").val()
    };
    return temp;
};

function createOptBtn(proId, status) {
    let html = "";
    if (status == "0" || status == "1") {
        html += "<a href=\"javascript:void(0);edit('" + proId + "')\" class=\"btn btn-primary btn-xs\">编辑</a>&nbsp;&nbsp;"
            + "<a href=\"javascript:void(0);deleteProRecord('" + proId + "')\" class=\"btn btn-darkorange btn-xs\" >删除</a>&nbsp;&nbsp;"
            + "<a href=\"javascript:void(0);decompose('" + proId + "')\" class=\"btn btn-purple btn-xs\" >分解</a>&nbsp;&nbsp;"
            + "<a href=\"javascript:void(0);setToApproval('" + proId + "')\" class=\"btn btn-maroon btn-xs\" >提交</a>&nbsp;&nbsp;";
    }
    if (status == "2") {
        html += "<a href=\"javascript:void(0);takeBack('" + proId + "')\" class=\"btn btn-darkorange btn-xs\" >收回</a>";
    }
    return html;
}

function takeBack(proId) {
    if (confirm("您确定要收回正在审批的项目记录吗？")) {
        $.ajax({
            url: "/set/proset/updateProRecord",
            type: "post",
            dataType: "json",
            data: {
                proId: proId,
                status: '0'
            },
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable("refresh");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }
            }
        });
    }
}

function setToApproval(proId) {
    if (confirm("您确定已分配项目任务交提交审批记录吗？")) {
        $.ajax({
            url: "/set/proset/setToApproval",
            type: "post",
            dataType: "json",
            data: {
                proId: proId,
                status: '2'
            },
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable("refresh");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }
            }
        });
    }
}


function edit(proId) {
    document.getElementById("form1").reset();
    $("#show_attach").empty();
    $("#attach").attr("data_value", "");
    ue.setContent("");
    $("#joinDept").attr("data-value", "");
    $("#taskUsers").attr("data-value", "");
    $("#proSort").attr("data-value", "");
    $("#createProjectModal").modal("show");
    $.ajax({
        url: "/ret/proget/getProRecordById",
        type: "post",
        dataType: "json",
        data: {proId: proId},
        success: function (data) {
            if (data.status == "200") {
                let info = data.list;
                for (let id in info) {
                    if (id == "attach") {
                        $("#attach").attr("data_value", info.attach);
                        createAttach("attach", 4);
                    } else if (id == "manager") {
                        $("#" + id).attr("data-value", info[id]);
                        $("#" + id).val(getUserNameByStr(info[id]));
                    } else if (id == "joinDept") {
                        $("#" + id).attr("data-value", info[id]);
                        $("#" + id).val(getDeptNameByDeptIds(info[id]));
                    } else if (id == "taskUsers") {
                        $("#" + id).attr("data-value", info[id]);
                        $("#" + id).val(getUserNameByStr(info[id]));
                    } else if (id == "remark") {
                        ue.setContent(info[id]);
                    } else if (id == "proSort") {
                        $("#" + id).attr("data-value", info[id]);
                        $.ajax({
                            url: "/ret/proget/getProSortById",
                            type: "post",
                            dataType: "json",
                            data: {sortId: info[id]},
                            success: function (data) {
                                if (data.status = "200") {
                                    $("#" + id).val(data.list.sortName);
                                } else if (data.status == "100") {
                                    layer.msg(sysmsg[data.msg]);
                                } else {
                                    console.log(data.msg);
                                }
                            }
                        });
                    } else {
                        $("#" + id).val(info[id]);
                    }
                }
                $(".js-send").unbind("click").click(function () {
                    updateProRecord(proId)
                })
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }

        }
    });
}
function deleteProRecord(proId) {
    if (confirm("您确定要删除当前项目记录吗？")) {
        $.ajax({
            url: "/set/proset/deleteProRecord",
            type: "post",
            dataType: "json",
            data: {proId: proId},
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable("refresh");
                    getProRecordStatusCountList();
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }

            }
        });
    }
}

function details(proId) {
    window.open("/app/core/project/projectdetails?proId=" + proId);
}

function decompose(proId) {
    window.open("/app/core/project/decompose?proId=" + proId);
}

var setting1 = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/proget/getProSortTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        //禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("menuTree"), nodes = zTree.getSelectedNodes(), v = "";
            vid = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].sortName + ",";
                vid += nodes[i].sortId + ",";
            }
            if (v.length > 0)
                v = v.substring(0, v.length - 1);
            if (vid.length > 0)
                vid = vid.substring(0, vid.length - 1);
            var idem = $("#proSort");
            idem.val(v);
            idem.attr("data-value", vid);
        }
    }
};

function createProApprovalUser() {
    $.ajax({
        url: "/ret/proget/getProApprovalUserList",
        type: "post",
        dataType: "json",
        success: function (data) {
            if (data.status == "200") {
                let infoList = data.list;
                if (infoList != undefined) {
                    for (let i = 0; i < infoList.length; i++) {
                        $("#approvalUser").append("<option value='" + infoList[i].accountId + "'>" + infoList[i].userName + "</option>")
                    }
                }
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }

        }
    });
}

function getProRecordStatusCountList() {
    $.ajax({
        url: "/ret/proget/getProRecordStatusCountList",
        type: "post",
        dataType: "json",
        success: function (data) {
            if (data.status == "200") {
                let info = data.list;
                $(".status0").html(info.total0);
                $(".status1").html(info.total1);
                $(".status2").html(info.total2);
                $(".status3").html(info.total3);
                $(".status4").html(info.total4);
                $(".status5").html(info.total5);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }

        }
    });
}
